import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { Spin, Pagination } from 'antd';
import { ApiService } from '../services/api';
import './NewsPage.css';

const NewsPage = () => {
  const navigate = useNavigate();
  const [newsArticles, setNewsArticles] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [currentPage, setCurrentPage] = useState(1);
  const [total, setTotal] = useState(0);
  const pageSize = 10;

  // 获取行业资讯列表
  useEffect(() => {
    const fetchNews = async () => {
      try {
        setLoading(true);
        setError(null);

        const response = await ApiService.getIndustryNewsListPage(currentPage, pageSize);

        if (response.code === '0000' && response.data) {
          // 转换API数据格式
          const formattedNews = response.data.map(item => ({
            id: item.newsId,
            title: item.newsTitle,
            summary: '', // API没有返回摘要，可以后续扩展
            date: item.newTime ? new Date(item.newTime).toLocaleString('zh-CN', {
              year: 'numeric',
              month: '2-digit',
              day: '2-digit',
              hour: '2-digit',
              minute: '2-digit'
            }) : '',
            image: item.picUrl || '📰' // 如果没有图片URL，使用默认图标
          }));

          setNewsArticles(formattedNews);
          setTotal(response.total || 0);
        } else {
          setError('获取行业资讯失败');
        }
      } catch (err) {
        console.error('获取行业资讯失败:', err);
        setError('网络请求失败');
      } finally {
        setLoading(false);
      }
    };

    fetchNews();
  }, [currentPage]);

  // 处理分页变化
  const handlePageChange = (page) => {
    setCurrentPage(page);
  };

  // 处理资讯点击
  const handleNewsClick = (newsId) => {
    navigate(`/news/${newsId}`);
  };

  if (loading) {
    return (
      <div className="news-page">
        <div className="container">
          <div className="page-header">
            <h1>行业资讯</h1>
            <p>了解最新的科技动态、行业趋势和技术发展</p>
          </div>
          <div className="loading-container">
            <Spin size="large" />
            <p>加载行业资讯中...</p>
          </div>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="news-page">
        <div className="container">
          <div className="page-header">
            <h1>行业资讯</h1>
            <p>了解最新的科技动态、行业趋势和技术发展</p>
          </div>
          <div className="error-container">
            <p>{error}</p>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="news-page">
      <div className="container">
        <div className="page-header">
          <h1>行业资讯</h1>
          <p>了解最新的科技动态、行业趋势和技术发展</p>
        </div>

        <div className="news-grid">
          {newsArticles.length > 0 ? (
            newsArticles.map(article => (
              <div key={article.id} className="news-card" onClick={() => handleNewsClick(article.id)}>
                <div className="news-image">
                  {article.image.startsWith('http') ? (
                    <img src={article.image} alt={article.title} className="news-img" />
                  ) : (
                    <div className="news-icon">{article.image}</div>
                  )}
                </div>
                <div className="news-content">
                  <h3 className="news-title">{article.title}</h3>
                  <div className="news-meta">
                    <span className="news-date">{article.date}</span>
                  </div>
                </div>
              </div>
            ))
          ) : (
            <div className="no-news">
              <p>暂无行业资讯</p>
            </div>
          )}
        </div>

        {/* 分页组件 */}
        {total > 0 && (
          <div className="pagination-container">
            <Pagination
              current={currentPage}
              total={total}
              pageSize={pageSize}
              onChange={handlePageChange}
              showSizeChanger={false}
              showTotal={(total, range) =>
                `第 ${range[0]}-${range[1]} 条，共 ${total} 条`
              }
            />
          </div>
        )}
      </div>
    </div>
  );
};

export default NewsPage;
